package com.xu.mb3;

import com.xu.mybatis.constant.MblConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * mybatis数据库连接
 *
 * @author xuguan
 * @since 2024/11/10
 */
@Slf4j
public class MbUtil {

    public static SqlSession openSqlSession(boolean autoCommit) {
        try {
            final InputStream is = Resources.getResourceAsStream(MblConstant.MYBATIS_CONFIG_NAME);
            final SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            return sqlSessionFactory.openSession(autoCommit);
        } catch (IOException e) {
            log.error("mybatis-config配置文件读取失败", e);
            throw new RuntimeException(e);
        }
    }

    public static void close(SqlSession sqlSession) {
        if (Objects.nonNull(sqlSession)) {
            sqlSession.close();
        }
    }
}
